<template>
  <div class="menu">
    <div class="menu-left" style="height: 777px;overflow-y: auto;margin-right: 10px;">
      <menuTree @handleNodeClickEmit = "handleNodeClick"/>
      <!-- <el-tree :data="tree" :props="defaultProps" :default-expand-all="true" :highlight-current = "true" :expand-on-click-node = "false" @node-click="handleNodeClick" /> -->
    </div>
    <div class="menu-right">
      <!-- 按钮组 -->
      <el-row class="M-B-5" ref="btnsRef">
        <el-button type="primary" @click="add('ADD')">添加菜单</el-button>
        <el-button type="primary" @click="batchChange">批量启/禁用</el-button>
        <el-button type="danger" @click="batchDel" >批量删除</el-button>
      </el-row>
      <el-table  :data="curChildrenLists" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="(item,index) in tableCols" :key="index" :prop="item.prop" :label="item.label" :min-width="item.minWidth">
          <template #default="scope">
            <div v-if="item.prop=='status'">
              <el-switch :model-value="scope.row.status==1?true:false" class="ml-2" style="--el-switch-on-color: #13ce66;" @click="batchChange(scope._index,scope.row)"/>
            </div>
            <div v-if="item.prop=='handle'">
              <el-button size="small" type="primary" @click="handleEdit(scope)">编辑</el-button>
              <el-button size="small" type="danger" @click="batchDel(scope.$index, scope.row)" >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <addMenu ref="addMenuRef"></addMenu>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs,onMounted } from 'vue'
import {useStore} from '@/store'
import {findMenuApi,createMenuApi,updateMenuApi,deleteMenuApi,changeStatusApi} from '@/request/menu'
import addMenu from '@/components/menu/addMenu.vue'
import menuTree from '@/components/menu/menuTree.vue'

export default defineComponent({
  name: 'Vuex',
  components:{addMenu,menuTree},
  setup() {
    const store = useStore()
    const reactiveData = reactive({
      curChildrenLists:[],
      // 表头
      tableCols:[
        {prop:'title',label:'菜单名',minWidth:100},
        {prop:'route_name',label:'路由',minWidth:80},
        {prop:'api_route_name',label:'请求API',minWidth:125},
        // {prop:'icon',label:'图标',minWidth:168},
        {prop:'type',label:'类型',minWidth:80},
        {prop:'status',label:'启/禁用',minWidth:80},
        {prop:'handle',label:'操作',minWidth:200},
      ],
      tree : [{
        id:0,
        label:'资源菜单',
        children:[]
      }]
    })
    
    let treeData:any = []
    if(store){
       treeData = store.state.userModule.menuTree
    }


    const handleNodeClick = async (data:any,treeData:any) => {
        if(data.id === 0) {
          reactiveData.curChildrenLists = treeData
        }else{
          const menu:any =  filterTree(treeData,[],data.id)
          reactiveData.curChildrenLists = menu[0]? menu[0].children:[]
        }
        console.log(reactiveData.curChildrenLists);
    }

    const filterTree = (tree:any, arr:any[] = [],id:number)=>{
        if (!tree.length) return []
        for (let item of tree) {
            // 循环数组，然后过滤数据
            // 如果该条数据type不为0时，跳出本次循环
            if (item.id !== id) continue
            // 如果满足条件时，用新node代替，然后把chilren清空
            let node = item
            // 然后添加到新数组中
            arr.push(node)
            // 如果有子节点，调用递归函数，并把空数组传给下一个函数
            // 利用引用数据类型的特性，实现浅拷贝
            // 递归函数过滤时会改变这个空数组数据，从而实现层级结构过滤
            if (item.children && item.children.length) {
                filterTree(item.children, node.children,id)
            }
        }
        return arr
    }

    //表格多选列表
    const selections = ref<any[]>([])
    const handleSelectionChange = (val: any[]) => {
      selections.value = val
      console.log(selections.value);
      
    }
    const addMenuRef = ref()
    // 创建
    const add = (Type:string,scope?:any) => {
      addMenuRef.value.trigger(Type,scope)
    }

    // 编辑
    const handleEdit = (scope:any) =>{
      add('EDIT',scope)
    }

    // 批量启用/禁用
    const batchChange = async (index?:any,row?:any) => {
      let ids:number[] = []
      if(row){
        ids = [row.id]
      }else{
        if(!selections.value.length){
          ElMessage({
            message:"请先选择数据",
            type:"warning"
          })
          return
        }
        ids = selections.value.map(item=>item.id)
      }
      let postData = {ids}
      const res = await changeStatusApi(postData)
      if(res.data.code === 1){
        ElMessage({
            message:"修改状态成功",
            type:"success"
          })
      }
    }

    // 删除 批量删除
    const batchDel = async (index?:any,row?:any) => {
      let ids:number[] = []
      if(row){
        ids = [row.id]
      }else{
        if(!selections.value.length){
          ElMessage({
            message:"请先选择数据",
            type:"warning"
          })
          return
        }
        ids = selections.value.map(item=>item.id)
      }
      ElMessageBox.confirm(
        '确定删除？','删除用户',
        {confirmButtonText: '确定',cancelButtonText: '取消',type: 'error',}
      ).then(async () => {
        const postData = {ids}
        const res = await deleteMenuApi(postData)
        if(res.data.code === 1){
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
      }).catch(() => {

      })
    }

    
    onMounted(()=>{
       reactiveData.curChildrenLists = treeData
    })
    

    return {
      ...toRefs(reactiveData),
      handleNodeClick,handleSelectionChange,handleEdit,batchChange,batchDel,add,
      addMenuRef
    }
  }
})
</script>

<style scoped lang="stylus">
.menu{
  display flex;
   &-left{
    width 20%
   }
   &-right{
    width 75%
   }
}
</style>
